package a66weding.com.jiehuntong.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.adapter.CommonAdapter;
import a66weding.com.jiehuntong.adapter.ViewHolder;
import a66weding.com.jiehuntong.beans.SongsBean;
import a66weding.com.jiehuntong.common.utils.Tools;

public class LocalMusicActivity extends BaseHomeActivity implements View.OnClickListener {
    private String currentUri = "";
    List<SongsBean> mSongsBeans = new ArrayList<SongsBean>();
    private MediaPlayer mediaPlayer;
    private TextView talk_none;
    private ListView allMusics;
    private CommonAdapter mCommonAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_music);
        initView();
        initData();
    }
    private void initData() {
        Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        if (cursor != null) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String uriData = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                if (uriData.endsWith(".mp3")||uriData.endsWith(".MP3")) {
                    SongsBean songsBean = new SongsBean(title, uriData);
                    mSongsBeans.add(songsBean);

                }
            }
            cursor.close();
        }
        if (mSongsBeans.size() > 0) {
            talk_none.setVisibility(View.GONE);
            mCommonAdapter = new CommonAdapter<SongsBean>(this, mSongsBeans, R.layout.item_local_music) {
                @Override
                public void convert(ViewHolder holder, SongsBean songsBean) {
                    TextView view = holder.getView(R.id.tv_songs);
                    view.setText(songsBean.getMusicName());
                    view.setCompoundDrawables(null, null, null, null);//全部默认不设置
                    if (currentUri.equals(songsBean.getMusicUri())) {
                        //新建Drawable
                        Drawable drawable = getResources().getDrawable(R.mipmap.checked_music);
                        //设置边界，否则无法显示
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        //设定DrawableRight
                        view.setCompoundDrawables(null, null, drawable, null);//画在右边
                    }
                }
            };
            allMusics.setAdapter(mCommonAdapter);
        } else {
            talk_none.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        //头部导航
        TextView tv_tools_dayplan_backcontent = (TextView) findViewById(R.id.tv_tools_dayplan_backcontent);
        LinearLayout llay_toolsheader_back = (LinearLayout) findViewById(R.id.llay_toolsheader_back);
        TextView tv_tools_dayplan_title = (TextView) findViewById(R.id.tv_tools_dayplan_title);
        TextView tv_tools_dayplan_addtype1 = (TextView) findViewById(R.id.tv_tools_dayplan_addtype1);
        ImageView img_tools_dayplan_backcontent = (ImageView) findViewById(R.id.img_tools_dayplan_backcontent);
        img_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setText("返回");
        tv_tools_dayplan_title.setText("音乐选择");
        tv_tools_dayplan_addtype1.setText("");
        tv_tools_dayplan_addtype1.setVisibility(View.VISIBLE);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        llay_toolsheader_back.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_addtype1.setOnClickListener(this);

        allMusics = (ListView) findViewById(R.id.lv_all_native_music);
        talk_none = (TextView) findViewById(R.id.tv_talk_none_music);
        allMusics.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SongsBean bean = mSongsBeans.get(position);
                currentUri = bean.getMusicUri();
                playMusic(currentUri);
                int childCount = allMusics.getChildCount();//获得listview总共的item数量
                for (int i = 0; i < childCount; i++) {
                    //获得item的内容信息
                    SongsBean bs = (SongsBean) allMusics.getAdapter().getItem(i);
                    TextView tv_songs = (TextView) allMusics.getChildAt(i);
                    if (currentUri.equals(bs.getMusicUri())) {
                        //新建Drawable
                        Drawable drawable = getResources().getDrawable(R.mipmap.checked_music);
                        //设置边界，否则无法显示
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        //设定DrawableRight
                        tv_songs.setCompoundDrawables(null, null, drawable, null);//画在右边
                    } else {
                        tv_songs.setCompoundDrawables(null, null, null, null);//不设置
                    }
                }
                mCommonAdapter.notifyDataSetChanged();
            }
        });
    }

    public void cancel_music(View v) {
        stopMusic();
        finish();
    }
    public void sure_music(View v) {
        if (!currentUri.isEmpty()) {
            Intent intent = new Intent();
            intent.putExtra("musicPath", currentUri);
            setResult(999, intent);
            finish();
            stopMusic();
        } else {
            Tools.showSimpleDialog(this, "暂无选择歌曲,是否关闭当前页面", "否", "是", new Tools.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    finish();
                    stopMusic();
                }
                @Override
                public void doCancel() {
                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopMusic();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (!currentUri.isEmpty()) {
                Tools.showSimpleDialog(this, "您已选择是否放弃?", "否", "是", new Tools.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        finish();
                        stopMusic();
                    }
                    @Override
                    public void doCancel() {
                        Intent intent = new Intent();
                        intent.putExtra("musicPath", currentUri);
                        setResult(999, intent);
                        finish();
                        stopMusic();
                    }
                });

                return true;//当更改选项后id不一致拦截返回事件
            } else {
                stopMusic();
                finish();
            }

        }
        return super.onKeyDown(keyCode, event);
    }


    //播放音乐
    private void playMusic(String url) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
            }
            mediaPlayer.stop();
            mediaPlayer.reset();
            //设置数据源
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
            //异步准备完成
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            stopMusic();
        }
    }

    // 停止音乐
    public void stopMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_toolsheader_back:
                finish();
                stopMusic();
                break;
            case R.id.img_tools_dayplan_backcontent:
                finish();
                stopMusic();
                break;
            case R.id.tv_tools_dayplan_backcontent:
                finish();
                stopMusic();
                break;
        }
    }
}